package com.tongda.core.message;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import com.tongda.core.vo.MessageVO;

/**
 * 消息中心配置
 */
public class MessageProcessClient {
	private ChannelFuture lastWriteFuture;
	private ClientBootstrap bootstrap;
	private MessageListener messageListener;
	public Channel channel;
	private final String host;
	private final int port;

	public MessageProcessClient(String host, int port,
			MessageListener messageListener) {
		this.host = host;
		this.port = port;
		this.messageListener = messageListener;
	}

	public void start() throws IOException {
		bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));

		bootstrap
				.setPipelineFactory(new MessagePipelineFactory(messageListener));

		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);
		// Start the connection attempt.
		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
				port));

		// Wait until the connection attempt succeeds or fails.
		channel = future.awaitUninterruptibly().getChannel();
		// if (!future.isSuccess()) {
		// future.getCause().printStackTrace();
		// bootstrap.releaseExternalResources();
		// return;
		// }

		for (int i = 0; i < 2; i++) {
			// lastWriteFuture = channel.write("hello mixi8er" + i + "\r\n");
			MessageVO vo = new MessageVO();
			vo.setName("abcd");
			vo.setDesc("hehe");
			channel.write(vo);
		}

	}

	public void stopQuitely() throws IOException {
		// follow the netty guide
		// Wait until all messages are flushed before closing the channel.
		if (lastWriteFuture != null) {
			lastWriteFuture.awaitUninterruptibly();
		}

		// Close the connection. Make sure the close operation ends because
		// all I/O operations are asynchronous in Netty.
		channel.close().awaitUninterruptibly();

		// Shut down all thread pools to exit.
		bootstrap.releaseExternalResources();
	}

}
